#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from tortoise import models, fields
from datetime import datetime
from decimal import Decimal

from settings.config import settings

class BaseModel(models.Model):
    id = fields.BigIntField(pk=True, index=True, description='主键')

    async def to_dict(self, m2m: bool = False, exclude_fields: list[str] | None = None):
        if exclude_fields is None:
            exclude_fields = []

        d = {}
        for field in self._meta.db_fields:
            if field not in exclude_fields:
                value = getattr(self, field)
                # 处理 Decimal 类型
                if isinstance(value, Decimal):
                    value = float(value)  # 或者 str(value)，根据需要选择
                # 处理 datetime 类型
                elif isinstance(value, datetime):
                    value = value.strftime(settings.DATETIME_FORMAT)
                d[field] = value
    
        if m2m:
            for field in self._meta.m2m_fields:
                if field not in exclude_fields:
                    values = [value for value in await getattr(self, field).all().values()]
                    for value in values:
                        value.update(
                            (k, v.strftime(settings.DATETIME_FORMAT))
                            if isinstance(v, datetime)
                            else (k, float(v)) if isinstance(v, Decimal)
                            else (k, v)
                            for k, v in value.items()
                        )
                    d[field] = values
        return d

    class Meta:
        abstract = True

class UUIDModel:
    hashed_id = fields.UUIDField(unique=True, pk=False)

class BaseCreatedUpdatedAtModel:
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_now=True)
    
class BaseCreatedUpdatedModel:
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_now=True)
    created_by = fields.CharField(max_length=30, index=True, description='创建者')
    updated_by = fields.CharField(max_length=30, index=True, description='更新者')